package com.gitee.jmash.oidc.client.web;

import java.util.UUID;
import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.oidc.client.oauth.OidcClient;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.servlet.http.HttpServletRequest;

public class OauthUtil {

  public static final String OIDC_STATE = "oidc.state";

  public static OidcClient getOidcClient() {
    return CDI.current().select(OidcClient.class).get();
  }

  public static String createAuthCodeUrl(HttpServletRequest req, String redirectPath,
      boolean silent) {
    return createAuthUrl(req, redirectPath, "code", silent);
  }

  public static String createAuthImplicitUrl(HttpServletRequest req, String redirectPath,
      boolean silent) {
    return createAuthUrl(req, redirectPath, "id_token", silent);
  }

  public static String createAuthHybridUrl(HttpServletRequest req, String redirectPath,
      boolean silent) {
    return createAuthUrl(req, redirectPath, "code id_token", silent);
  }

  public static String createAuthUrl(HttpServletRequest req, String redirectPath,
      String responseType, boolean silent) {
    OidcClient oidcClient = getOidcClient();
    String state = UUIDUtil.uuid32(UUID.randomUUID());
    req.getSession().setAttribute(OIDC_STATE, state);
    String scope = silent ? "openid" : "openid profile email phone address";
    String contextPath = req.getContextPath();
    if (req.getContextPath().length() > 0 && !req.getContextPath().startsWith("/")) {
      contextPath = "/" + req.getContextPath();
    }
    String redirectUri = String.format("%s://%s:%d%s/%s", req.getScheme(), req.getServerName(),
        req.getServerPort(), contextPath, redirectPath);
    return oidcClient.authCodeUrl(responseType, scope, state, redirectUri);
  }



}
